import SockJS from "sockjs-client";
import Stomp from "webstomp-client";
export default {
  name: "websocket",
  data: function() {
    return {
      websocket: {
        received_messages: [],
        send_message: null,
        connected: false
      }
    };
  },
  methods: {
    send(direction) {
      if (this.stompClient && this.stompClient.connected) {
        const msg = { name: this.send_message };
        this.stompClient.send(direction, JSON.stringify(msg), {});
      }
    },
    connect(url, isHttp, callback) {
      let self = this;
      if (isHttp) {
        this.socket = new SockJS(url);
        this.stompClient = Stomp.over(this.socket);
      } else {
        this.stompClient = Stomp.client(url);
      }
      this.stompClient.connect(
        {},
        frame => {
          self.connected = true;
          //console.log(frame);
          self.stompClient.subscribe("/topic/model", async tick => {
            /**
             * self.websocket.received_messages.push(JSON.parse(tick.body));
             * let notification = new Notification("执行完成", {
             *  body: "执行完成,点击查看结果
             * });
             * 生成通知消息
             * let key = JSON.parse(tick.body).operationId;
             */
            callback(tick);
          });
        },
        error => {
          //console.log(error);
          this.connected = false;
        }
      );
    },
    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect();
      }
      this.connected = false;
    },
    tickleConnection() {
      this.connected ? this.disconnect() : this.connect();
    }
  }
};
